package main

import (
	"fmt"
	"log"
	"net"
	"net/rpc"
)

type (
	GetUserReg struct {
		ID string `json:"id"`
	}
	GetUserRes struct {
		ID       int    `json:"id"`
		Username string `json:"username"`
		Password string `json:"password"`
	}
)

type UserServer struct{}

// UserServer.GetUser

func (*UserServer) GetUser(reg GetUserReg, res *GetUserRes) error {
	if u, ok := Users[reg.ID]; ok {
		*res = GetUserRes{ID: u.ID, Username: u.Username, Password: u.Password}
		return nil
	}
	return fmt.Errorf("user not found")
}

func main() {
	// 创建服务
	server := new(UserServer)
	// 注册服务到RPC服务器
	rpc.Register(server)

	// 监听
	listener, err := net.Listen("tcp", ":8000")
	if err != nil {
		fmt.Println("error listening:", err)
		return
	}

	log.Println("服务启动成功")

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Println("接收客户端连接失败", err)
			continue
		}

		// 并发处理客户端请求
		go rpc.ServeConn(conn)
	}
}
